<template>
  <div>
    <div>
      <el-input style="width: 200px; margin: 0 5px" placeholder="标题" v-model="title"></el-input>
      <el-button type="primary" @click="activityList(1)">查询</el-button>
      <el-button type="danger" @click="resetting">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue' , color: '#666'}"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" align="center"></el-table-column>
      <el-table-column prop="title" label="标题" align="center"></el-table-column>
      <el-table-column label="封面" align="center">
        <template v-slot="scope">
          <el-image style="width: 80px; height: 50px;" v-if="scope.row.image"
                    :src="scope.row.image" :preview-src-list="[scope.row.image]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容" align="center">
        <template v-slot="scope">
          <el-button @click="showContent(scope.row.content)" size="mini">显示内容</el-button>
          <el-button @click="$router.push('/newsDetail?id=' +scope.row.id)" size="mini">详情页</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="发布人" align="center"></el-table-column>
      <el-table-column :formatter="formatDate" prop="startTime" label="开始时间" align="center"></el-table-column>
      <el-table-column :formatter="formatDate" prop="enddTime" label="结束时间" align="center"></el-table-column>
      <el-table-column label="是否公开" align="center">
        <template v-slot="scope">
          <el-switch v-model="scope.row.status" @change="changeOpen(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="新闻信息" :visible.sync="AddDialogFormVisible" width="60%" @close="closeDialog"
               :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px" style="margin-right: 20px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="标题"></el-input>
        </el-form-item>
        <div style="text-align: center;margin-left: 55px" >
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8888/file/upload"
              :headers="{ token: user.token} "
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
            <el-image v-if="form.image" :src="form.image" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <!--            <el-button type="primary">上传头像</el-button>-->
          </el-upload>
        </div>
        <el-form-item label="内容" prop="content">
          <!--          <el-input v-model="form.content" placeholder="内容"></el-input>-->
          <div id="editor"></div>
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="开始时间" prop="startTime">
            <!--          <el-input v-model="form.rentDate" placeholder="租借日期"></el-input>-->
            <el-date-picker
                v-model="form.startTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                default-time="12:00:00">
            </el-date-picker>

          </el-form-item>
          <el-form-item label="结束时间" prop="enddTime">
            <!--          <el-input v-model="form.returnDate" placeholder="归还日期"></el-input>-->
            <el-date-picker
                v-model="form.enddTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                default-time="12:00:00">
            </el-date-picker>
          </el-form-item>
        </div>

        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" @click="AddDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog title="查看内容" :visible.sync="AddDialogFormVisible1" width="60%">
      <el-card class="w-e-text">
        <div v-html="content"></div>
      </el-card>
      <div style="text-align: center;margin-top: 20px">
        <el-button type="primary" @click="AddDialogFormVisible1 = false">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import E from "wangeditor"
import hljs from 'highlight.js'

export default {
  name: "Activity",
  data() {
    return {
      tableData: [], // 所有的数据
      pageIndex: 1, // 当前的页码
      pageSize: 5, // 每页显示的个数
      title: '', // 分页查询的用户名
      total: 0, // 数据的总条数
      AddDialogFormVisible: false,
      user: JSON.parse(localStorage.getItem('power-user') || '{}'), // 存储缓存
      form: {image: ''}, // 存储表单缓存
      rules: {
        // title: [{required: true, message: '请输入标题', trigger: 'blur'},],
      },
      ids: [],
      editor: null,
      content: '',
      AddDialogFormVisible1: false,
    }
  },
  created() {
    this.activityList()
  },
  methods: {
    // 滑块开关
    changeOpen(form){
      this.form = JSON.parse(JSON.stringify(form)) // 深拷贝
      this.sendSaveRequest() // 调用更新的方法，直接发请求，不用校验
    },
    //  时间格式化专用
    formatDate(row, column) {
      // 获取单元格数据
      let data = row[column.property];
      if (data == null) {
        return null;
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
    },

    // 查看内容
    showContent(content) {
      this.content = content
      this.AddDialogFormVisible1 = true // 打开弹窗
    },

    // 弹窗关闭前的回调
    closeDialog() {
      // 销毁编辑器
      this.editor.destroy()
      this.editor = null
    },

    // 批量删除
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning("请选择要删除的数据")
        return
      }
      // 二次确认
      this.$confirm('您确认删除这些数据吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/activity/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.activityList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },

    handleSelectionChange(rows) { // 当前选中行的所有数据
      console.log(rows)
      this.ids = rows.map(v => v.id)
      // console.log(ids)
    },

    // 单个删除
    del(id) {
      // 二次确认
      this.$confirm('您确认删除吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/activity/delete/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.activityList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },

    // 设置富文本的一些配置
    setRichText() {
      // #editor 就表示上面弹窗里的id="editor"
      this.$nextTick(() => {
        this.editor = new E(`#editor`) // 初始化富文本区域
        this.editor.highlight = hljs
        this.editor.config.uploadImgServer = 'http://localhost:8888/file/editor/upload'
        this.editor.config.uploadFileName = 'file' // 这里对应后台的返回的对象
        this.editor.config.uploadImgHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadImgParams = {
          type: 'img'
        }
        this.editor.config.uploadVideoServer = 'http://localhost:8888/file/editor/upload'
        this.editor.config.uploadVideoName = 'file' // 这里对应后台的返回的对象
        this.editor.config.uploadVideoHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadVideoParams = {
          type: 'video'
        }
        this.editor.create() // 创建
      })
    },

    // 图片赋值
    handleAvatarSuccess(response, file) {
      // 把封面属性换成上传的图片的链接
      // this.form.image = response.data
      this.form.image = URL.createObjectURL(file.raw)
      //  根据数据刷新节点
      this.$forceUpdate() //组件嵌套太深 无法自动更新 强制更新视图
    },

    handleEdit(row) { // 编辑数据
      // 给form对象赋值，注意要深拷贝数据
      this.form = JSON.parse(JSON.stringify(row))
      // 打开弹窗
      this.AddDialogFormVisible = true
      this.setRichText() // 调用富文本上传配置

      // setTimeout延时加载，等里面的内容加载好
      setTimeout(() => {
        this.editor.txt.html(row.content) // 设置富文本内容
      }, 0)
    },

    handleAdd() { // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.AddDialogFormVisible = true // 打开弹窗
      // #editor 就表示上面弹窗里的id="editor"
      this.setRichText() // 调用富文本上传配置
    },

    sendSaveRequest(){
      this.$request({
        // 因为修改是从行内元素拿到的，有id，因此可以作此判断
        // 判断有没id，如果有id说明是修改的方法，如果没有则是新增的方法
        method: this.form.id ? 'PUT' : 'POST',
        url: this.form.id ? '/activity/update' : '/activity/add',
        data: this.form
      }).then(res => {
        if (res.code === '200') {
          this.$message.success('保存成功')
          this.activityList(1)
          this.AddDialogFormVisible = false
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    save() { // 保存按钮触发的逻辑 它会触发新增或者修改
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          // 获取编辑框的内容
          let content = this.editor.txt.html()
          this.form.content = content
          this.sendSaveRequest()
        }
      })
    },

    resetting() {
      this.title = ''
      this.activityList()
    },

    activityList(pageIndex) { // 分页查询
      if (pageIndex) {
        this.pageIndex = pageIndex
      }
      request.get('/activity/selectByPage', {
        params: {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          title: this.title,
        }
      }).then(res => {
        if (res.code == '200') {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },

    handleCurrentChange(pageIndex) {
      // 赋值
      this.pageIndex = pageIndex
      // 调用分页查询方法
      this.activityList()
    }
  },
}
</script>

<style scoped>
/deep/ .avatar-uploader {
  /*border-radius: 50%;*/
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  /*border-radius: 50%;*/
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  max-width: 400px;
  width: 400px;
  height: 220px;
  line-height: 220px;
  text-align: center;
  /*border-radius: 50%;*/
}

.avatar {
  /*width: 178px;*/
  /*height: 178px;*/
  max-width: 400px;
  width: 400px;
  height: 220px;
  display: block;
  /*border-radius: 50%;*/
}
</style>